package com.securecrt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Properties;

import org.apache.commons.net.ftp.FTPClient;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.securecrt.sql.SQLHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;

public class ssh1 extends Activity{
	
	Spinner protocol;
	Spinner cipher;
	public String Server="ftp.elisoft.co.kr";
	EditText etHostname;
	EditText etPort;
	EditText etUsername;
	EditText etPassword;
	Button btloginssh1;
	public FTPClient mFTPClien=null;
    Session session;
    Channel channel;
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais;
    Button btBack, btHome,btvn,bten,btkr;
	TextView tvprotocol,tvHostname,tvPort,tvUsername,tvPassword,tvlinksession;
	private boolean checked=false;
	SQLHelper eventsData;
	CheckBox save_session;
	ProgressDialog pro;
//	private ssh2 ssh2=new ssh2();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ssh1);
        
        protocol = (Spinner)findViewById(R.id.protocol);
        etHostname=(EditText)findViewById(R.id.etHostname);
        etPort=(EditText)findViewById(R.id.etPort);
        etUsername=(EditText)findViewById(R.id.etUsername);
        etPassword=(EditText)findViewById(R.id.etPassword);
        btloginssh1=(Button)findViewById(R.id.btloginssh1);
                
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.protocol ,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        protocol.setAdapter(adapter);
        protocol.setSelection(2);
        protocol.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String name = parent.getItemAtPosition(position).toString();
				if(name.equals("ssh1")){
					return;
				}
				String classSelected = "com.securecrt." + name.toUpperCase();
				Intent intent = new Intent(classSelected);
				startActivity(intent);
				finish();
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        cipher = (Spinner)findViewById(R.id.cipher);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.cipher ,android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cipher.setAdapter(adapter2);
        cipher.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        btloginssh1.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				OpenTerminal();
			}
        	
        });
        
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);
		btBack.setOnClickListener(onBackClick());
		btHome.setOnClickListener(onHomeClick());

		tvprotocol=(TextView)findViewById(R.id.tvprotocol);
		tvHostname=(TextView)findViewById(R.id.tvHostname);
		tvPort=(TextView)findViewById(R.id.tvPort);
		tvUsername=(TextView)findViewById(R.id.tvUsername);
		tvPassword=(TextView)findViewById(R.id.tvPassword);
		
        btvn=(Button)findViewById(R.id.btvn);btvn.setOnClickListener(onClickbtvn());
        bten=(Button)findViewById(R.id.bten);bten.setOnClickListener(onClickbten());
        btkr=(Button)findViewById(R.id.btkr);btkr.setOnClickListener(onClickbtkr());
        save_session=(CheckBox)findViewById(R.id.save_session);
        save_session.setOnCheckedChangeListener(ChecKedChangeListener);
        eventsData=new SQLHelper(this);
        
        tvlinksession=(TextView)findViewById(R.id.tvlinksession);
        tvlinksession.setOnClickListener(OnClickLinksession);
    }
    private OnCheckedChangeListener ChecKedChangeListener=new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			if(buttonView.isChecked()){
				checked=true;
			}else{
				checked=false;
			}
		}
	};
    private OnClickListener OnClickLinksession=new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			passSaveSession();
		}
	};
    private void passSaveSession(){
    	Intent i=new Intent(this, SaveSession.class);
    	i.putExtra("host",tvHostname.getText().toString());
		i.putExtra("port", tvPort.getText().toString());
		i.putExtra("user", String.valueOf(tvUsername.getText().toString()));
		i.putExtra("pass", tvPassword.getText().toString());
    	startActivity(i);
    }
    private void refresh() {
        finish();
        Intent myIntent = new Intent(ssh1.this, ssh1.class);
        startActivity(myIntent);
    }
    private void changuageLang(String lang){
		Locale locale=new Locale(lang);
        Locale.setDefault(locale);
        Configuration config=new Configuration();
        config.locale=locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
    private OnClickListener onClickbtvn(){
    	OnClickListener onClickbtvn=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("vn");refresh();
			}
		};
    	return onClickbtvn;
    }
    private OnClickListener onClickbten(){
    	OnClickListener onClickbten=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("en");refresh();
			}
		};
    	return onClickbten;
    }

    private OnClickListener onClickbtkr(){
    	OnClickListener onClickbtkr=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("kr");refresh();
			}
		};
    	return onClickbtkr;
    }
    private void saveSessionActive(){
    	SQLiteDatabase db=eventsData.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put(SQLHelper.HOSTNAME, etHostname.getText().toString());
		values.put(SQLHelper.PORT, etPort.getText().toString());
		values.put(SQLHelper.USERNAME, String.valueOf(etUsername.getText().toString()));
		values.put(SQLHelper.PASSWORD, etPassword.getText().toString());
		db.insert(SQLHelper.TABLE, null, values);
    }
    private void OpenTerminal(){
    	
    	if(etHostname.getText().toString().trim().equals("")){
    		Utils.showErrorMessage(ssh1.this,"Hostname is not empty!");
    		return;
		}
    	if(etUsername.getText().toString().trim().equals("")){
    		Utils.showErrorMessage(ssh1.this,"Username is not empty!");
    		return;
		}
    	if(etPassword.getText().toString().trim().equals("")){
    		Utils.showErrorMessage(ssh1.this,"Password is not empty!");
    		return;
		}
    	final String sPort=etPort.getText().toString().trim();
    	boolean isBadPort=false;
    	int iPort=0;
    	try{
    		iPort=Integer.parseInt(sPort);
    	}
    	catch (Exception e) {
			isBadPort=true;
		}
    	if(iPort<=0||iPort>=65535){
    		isBadPort=true;
    	}
    	if(isBadPort){
    		Utils.showErrorMessage(ssh1.this,"Bad port number!");
    		return;
    	}
    	Editor ed=this.getPreferences(0).edit();
    	ed.putString("server", etHostname.getText().toString());
    	ed.putString("port", etPort.getText().toString());
    	ed.putString("username", etUsername.getText().toString());
    	ed.putString("password", etPassword.getText().toString());
    	ed.commit();
    	loadingShow();
    	//pro=ProgressDialog.show(this, "", "Please wait...");
    	Thread t = new Thread(new Runnable(){
            public void run() {
                try{
				    	if(connectSSH(etHostname.getText().toString(), Integer.parseInt(etPort.getText().toString()), etUsername.getText().toString(), etPassword.getText().toString())){
							if(checked){
								//save session
								saveSessionActive();
							}
							String classSelected = "com.securecrt.TERMINAL";
					    	Intent i=new Intent(classSelected);
					    	i.putExtra("server", etHostname.getText().toString());
					    	i.putExtra("port", String.valueOf(sPort));
					    	i.putExtra("user", etUsername.getText().toString());
					    	i.putExtra("pass", etPassword.getText().toString());
					    	i.putExtra("cipher", cipher.getSelectedItem().toString());
					    	startActivity(i);
							//Toast.makeText(this,"SSH Connect Success.", Toast.LENGTH_LONG).show(); 
							session.disconnect();
				    	}else{
				    		pro.dismiss();
							//Utils.showErrorMessage(ssh1.this,"SSH Connect Fault.");
				    		Toast.makeText(ssh1.this,"SSH Connect Fault.", Toast.LENGTH_SHORT).show();			
							return;
						}
                }catch (Exception e) {
					e.printStackTrace();
				}
                pro.dismiss();
            }
        });
        t.start();

	}

    private void loadingShow(){
    	pro=ProgressDialog.show(this, "", "Please wait...");
    	
    }
    public boolean connectSSH(String host, int port, String username, String password){
        
        JSch jsch = new JSch();
        boolean  flag=false;
          try {
              session = jsch.getSession(username, host, port);
              session.setPassword(password);
              String CIPHER = cipher.getSelectedItem().toString();
              Properties properties = new Properties();
              if(CIPHER != null && !CIPHER.equals("none")){
            	  properties.put("cipher.s2c", CIPHER); 
            	  properties.put("cipher.c2s", CIPHER);
            	  session.setConfig("CheckCiphers", CIPHER);
              }
              properties.put("3des-cbc","com.jcraft.jsch.jce.TripleDESCBC");
              properties.put("aes128-cbc", "com.jcraft.jsch.jce.AES128CBC");
              properties.put("blowfish-cbc","com.jcraft.jsch.jce.BlowfishCBC");
              properties.put("StrictHostKeyChecking", "no");
              session.setConfig(properties);
              session.connect(30000);
              if(session.isConnected())
            	  flag = true;
              
          } catch (JSchException e) {
              // TODO Auto-generated catch block
              Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
              //flag = false;
          }
          return flag;
  }
    
	
	private OnClickListener onBackClick() {
		OnClickListener onBackClick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				moveTaskToBack(true);
				finish();
				System.exit(0);
			}
		};
		return onBackClick;
	}
	
	private OnClickListener onHomeClick() {
		OnClickListener onHomeClick = new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
				System.exit(0);
			}
		};
		return onHomeClick;
	}
	
}
